package com.godfeer.admin.modular.file.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpMethodName;
import com.godfeer.core.base.controller.BaseController;
import com.godfeer.core.util.DateUtil;
import com.godfeer.admin.modular.file.service.IUploadService;
import com.godfeer.admin.modular.system.model.Upload;
import com.godfeer.admin.myconfig.myenum.DBEnum;
import com.godfeer.admin.myconfig.myenum.FileEnum;
import com.godfeer.admin.myconfig.properties.COSFileProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

@Api(value = "文件操作")
@RestController
public class FileController extends BaseController {

    @Autowired//注入COS
    private COSClient cosClient;

    @Autowired
    private IUploadService uploadService;

    @Autowired
    private COSFileProperties cosFileProperties;


    @ApiOperation(value = "文件上传测试",notes = "/fileupload")
    @RequestMapping(value = "/fileupload",method = RequestMethod.POST)
    public Object uploadFile(@ApiParam(required = true)MultipartFile file) throws IOException{
        String FILENAMW_PREFFIX = "";//文件名拼接字符串前缀
        String FILE_NAME = "";//文件名
        String PATH = cosFileProperties.getPath();
        //文件是否选择
        if(file == null){
            return getErrorTip(FileEnum.EMPTY.getMessage(),"");
        }
        String originFileName = file.getOriginalFilename();//文件名
        //判断文件是视频文件还是图片文件
        if(originFileName != null && originFileName != ""){
            String suffix = null;
            try{
                suffix = originFileName.split("\\.")[1];
            }catch(ArrayIndexOutOfBoundsException e){
                return getErrorTip("请选择mp4格式的视频文件或jpg格式的图片文件","");
            }
            if(suffix != null && suffix != ""){
                if("jpg".equals(suffix) || "png".equals(suffix)){
                    PATH += "image/";
                }else if("mp4".equals(suffix)){
                    PATH += "video/";
                }else{
                    return getErrorTip("请选择mp4格式的视频文件或jpg格式的图片文件",originFileName);
                }
            }
        }
        FILENAMW_PREFFIX = UUID.randomUUID().toString().replaceAll("-", "") + "-";//获取UUID
        FILE_NAME = FILENAMW_PREFFIX + originFileName; //COS文件名
        //创建临时文件
        final File tempFile = File.createTempFile(FILENAMW_PREFFIX,originFileName);
        try{
            //写入临时文件
            file.transferTo(tempFile);
        }catch(IOException e){
            e.printStackTrace();
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }
        //发送到云服务器
        URL url = null;
        try{
            cosClient.putObject(cosFileProperties.getBucket(), PATH + FILE_NAME, tempFile);
            Date expiration = new Date(new Date().getTime() + 365 * 24 * 60 * 60 * 1000);//时间365天
            //获取文件上传后的路径
            url = cosClient.generatePresignedUrl(cosFileProperties.getBucket(),PATH+FILE_NAME,expiration,HttpMethodName.GET);
        }catch(CosServiceException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }catch(CosClientException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),"");
        }
        //设置插入文件的一些信息
        Upload upload = new Upload();
        upload.setName(PATH + FILE_NAME);//文件名
        upload.setType(file.getContentType());//文本类型
        upload.setCreatetime(DateUtil.getTime());//创建时间
        upload.setAddress(url.toString());//设置文件路径
        upload.setLength(file.getSize()/1024 < 1 ? 1 : (file.getSize()/1024));//设置文件的大小
        try{
            uploadService.insert(upload);//插入文件信息
        }catch(Exception e){
            return getErrorTip(DBEnum.DEFAULT.getMessage(),upload);
        }
        return getSuccessTip(FileEnum.SUCCESS.getMessage(),upload);
    }

    //删除文件
    public void deleteFile(Upload upload) throws CosClientException,CosServiceException{
        String fileName = upload.getName();
        cosClient.deleteObject(cosFileProperties.getBucket(), fileName);
    }

    //修改文件
    @RequestMapping("/updateFile")
    public Object updateFile(Upload upload,@RequestParam(value="file",required = true) MultipartFile file){
        try{
            uploadFile(file);
        }catch(IOException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),e.toString());
        }
        //删除原本的文件
        try{
            deleteFile(upload);
        }catch(CosServiceException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),e.toString());
        }catch(CosClientException e){
            return getErrorTip(FileEnum.DEFAULT.getMessage(),e.toString());
        }
        //删除数据库中的记录...
        try{
            uploadService.deleteFileByName(upload);
        }catch(Exception e){
            return getErrorTip(DBEnum.DEFAULT.getMessage(),upload);
        }
        return getSuccessTip(DBEnum.SUCCESS.getMessage(),upload);
    }
}
